package com.sutong.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.sutong.common.service.RemoteUserInterfaceInfoService;
import com.sutong.common.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR;

/**
 * 获取处理响应体
 *
 * @author sutong
 * @date 2024-07-16 22:45
 */
@Slf4j
@Component
public class HandleResponseBodyLogFilter implements GlobalFilter, Ordered {

    @DubboReference
    private RemoteUserInterfaceInfoService remoteUserInterfaceInfoService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();
        ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (Objects.equals(getStatusCode(), HttpStatus.OK) && body instanceof Flux) {
                    // 获取响应 ContentType
                    String responseContentType = exchange.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);
                    // 记录 JSON 格式数据的响应体
                    if (!StrUtil.isEmpty(responseContentType) && StrUtil.containsAny(responseContentType, MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE)) {
                        Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                            DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                            DataBuffer join = dataBufferFactory.join(dataBuffers);
                            byte[] content = new byte[join.readableByteCount()];
                            join.read(content);
                            DataBufferUtils.release(join);
                            // String responseData = new String(content, StandardCharsets.UTF_8);
                            // log.info("response data: {}", responseData);
                            String accessKey = exchange.getAttribute(Constant.ACCESS_KEY_STR);
                            Long interfaceId = exchange.getAttribute(Constant.INTERFACE_ID_STR);
                            return bufferFactory.wrap(handleResponseBody(content, accessKey, interfaceId));
                        }));
                    }
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(responseDecorator).build());
    }

    /**
     * 处理响应体，返回新的响应体
     */
    private byte[] handleResponseBody(byte[] content, String accessKey, Long interfaceId) {
        // 响应体
        String responseData = new String(content, StandardCharsets.UTF_8);
        log.info("response data: {}", responseData);
        // TODO 根据接口返回值判断是否成功，成功则去+1
        // 调用成功，接口调用次数+1
        remoteUserInterfaceInfoService.callInterfaceCount(accessKey, interfaceId);
        return content;
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 1;
    }

}
